package com.hs.jhzd.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hs.jhzd.entity.ContentType;
import com.hs.jhzd.repository.ContentTypeRepository;

@Controller
@RequestMapping("/ct")
public class ContentTypeController {

  @Autowired
  private ContentTypeRepository repository;

  @Value("${jsbh}")
  private String jsbh;

  @RequestMapping("/admin/main")
  public String mainPage(Model model) {
    List<ContentType> contentTypes = repository.findAll();
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("contentTypes", contentTypes);
    return "content-type-list";
  }

  @RequestMapping("/findAll")
  @ResponseBody
  public List<ContentType> findAll() {
    return repository.findAll();
  }

  @RequestMapping("/save")
  @ResponseBody
  public boolean save(ContentType contentType) {
    repository.save(contentType);
    return true;
  }

  @RequestMapping("/delete")
  @ResponseBody
  public boolean delete(@RequestParam(required = true) Long id) {
    repository.deleteById(id);
    return true;
  }

  @RequestMapping("/findBySubType")
  @ResponseBody
  List<ContentType> findBySubType(@RequestParam(required = true) String subType) {
    return repository.findBySubType(subType);
  }

  @RequestMapping("/findById")
  @ResponseBody
  ContentType findById(@RequestParam(required = true) Long id) {
    Optional<ContentType> contentType = repository.findById(id);
    return contentType.isPresent() ? contentType.get() : null;
  }

  @RequestMapping("/findSubTypeByName")
  @ResponseBody
  String findSubTypeByName(@RequestParam(required = true) String name) {
    return repository.findSubTypeByName(name);
  }
}
